package com.risenetsoft.elasticsearch.api;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * TransportClient是Java客户端操作的入口，所有的内容都需要用该对象去执行
 * 演示如何创建客户端连接：一般方式和集群方式
 * Created by Zhanggd on 2017/8/9.
 */
public class TransportClientDemo {
    public static final String CLUSTER_NAME = "elasticsearch"; //实例名称
    private static final int PORT = 9300;  //端口
    //可以有多个，集群方式
    private static final String IP = "192.168.190.104";

    //1.设置集群名称：默认是elasticsearch，并设置client.transport.sniff为true，
    // 使客户端嗅探整个集群状态，把集群中的其他机器IP加入到客户端中
    private static Settings settings = Settings.builder()
            .put("cluster.name", CLUSTER_NAME)//设置集群名称，以该名称查找
            .put("client.transport.sniff", true)
            .put("client.transport.ping_timeout", "120s")
            .build();

    //私有的全局变量
    private static TransportClient client;

    //静态块初始化
    static {
        try {
            client = new PreBuiltTransportClient(settings)
                    //添加两个地址
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(IP), PORT))
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(IP),PORT));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

}
